package nodelist

import (
	"bytes"
	"log"
	"strconv"
)

// https://leetcode-cn.com/leetbook/read/top-interview-questions-medium/xvdwtj/
// 偶数和奇数链表组合
// 算法：直接遍历
func oddEvenList(head *ListNode) *ListNode {
	if nil == head {
		return nil
	}
	newHead := new(ListNode)
	oddNode := head
	currentNode := newHead
	currentNode = setListNode(oddNode, currentNode)
	evenNode := head.Next
	setListNode(evenNode, currentNode)
	return newHead.Next
}

// 循环设置链表逻辑
func setListNode(oldNode, newNode *ListNode) (currentNode *ListNode) {
	currentNode = newNode
	for nil != oldNode {
		newNext := new(ListNode)
		newNext.Val = oldNode.Val
		currentNode.Next = newNext
		currentNode = newNext
		oldNode = oldNode.Next
		if nil == oldNode {
			break
		}
		oldNode = oldNode.Next
	}
	return
}

// 数据结构: 链表
type ListNode struct {
	Val  int
	Next *ListNode
}

// 生成一个新链表
func NewListNode(arr []int) (head *ListNode) {
	if len(arr) == 0 {
		return
	}
	head = new(ListNode)
	head.Val = arr[0]
	currentNode := head
	for index := 1; index < len(arr); index++ {
		currentNode.Next = new(ListNode)
		currentNode = currentNode.Next
		currentNode.Val = arr[index]
	}
	return
}

// 打印链表
func PrintListNode(head *ListNode) {
	buf := bytes.Buffer{}
	buf.WriteString("[")
	currentNode := head
	for nil != currentNode {
		if currentNode != head {
			buf.WriteString(",")
		}
		buf.WriteString(strconv.Itoa(currentNode.Val))
		currentNode = currentNode.Next
	}
	buf.WriteString("]")
	log.Println(buf.String())
}
